package com.cm.etax.tianjin;

import com.cm.etax.BaseEtax;
import com.cm.etax.EtaxConfig;
import com.cm.etax.FunctionResult;
import com.cm.etax.exceptions.EtaxException;
import com.cm.etax.tianjin.bean.SysApiResponse;
import com.cm.kits.RandomKits;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import com.cm.rpa.beans.Point;

/**
 * 自然人登录（TODO 后期完善）
 *
 * @author LWang 2023.01.30
 * @since 1.0.0
 */
@Slf4j
public class HumanLoginFunction extends LoginFunction {

    public HumanLoginFunction(BaseEtax etax) {
        super(etax);
    }

    /**
     * 自然人登录
     *
     * @param personId       自然人账号
     * @param personPassword 自然人密码
     * @return 登录结果
     */
    public FunctionResult<Object> login(String personId, String personPassword) {
        config().setLoginType(EtaxConfig.LOGIN_TYPE_HUMAN);
        try {
            rpa().visit(config().getMainUrl());
            tryLogout();
            rpa().visit(config().getDomain());
            tryCloseNotices();
            toLoginPage();
            tryLogin(personId, personPassword);
            ignoreSetPassword();
            rpa().sleep(SLEEP_TIME);
            if (!StringUtils.contains(rpa().url(), config().getHomeUri())) {
                throw new EtaxException("出现未预料的登录流程！");
            }
            return new FunctionResult<>(true, "登录成功。", null);
        } catch (Exception e) {
            return handleException(e, "登录失败，");
        }
    }

    /**
     * 尝试进行自然人登录
     *
     * @param personId       自然人账号
     * @param personPassword 自然人密码
     */
    protected void tryLogin(String personId, String personPassword) {
        rpa().click(rpa().findElementWithInnerText("自然人业务", By.cssSelector("div.justifyCenterEnd > span"), WAIT_TIME));
        rpa().click(rpa().findElementWithInnerText("用户名登录", By.cssSelector("div.card > div"), WAIT_TIME));
        // 8. 输入账号，密码
        rpa().sendKey(By.cssSelector("input[placeholder=\"用户名\"]"), personId, true, WAIT_TIME);
        rpa().sendKey(By.cssSelector("input[placeholder=\"个人用户密码(初始密码为证件号码后六位)\"]"), personPassword, true, WAIT_TIME);
        // 9. 滑动验证
        var dragHandler = rpa().findElement(By.cssSelector("div.drag > div.handler"), WAIT_TIME);
        rpa().moveTo(dragHandler);
        var drag = rpa().findElement(By.cssSelector("div.drag"));
        var handlerRect = rpa().sumElementRectangle(drag);
        rpa().dragTo(
                new Point(
                        RandomKits.nextDouble(handlerRect.rightTop().x(), handlerRect.rightTop().x() + MOUSE_OFFSET),
                        RandomKits.nextDouble(handlerRect.rightTop().y() - MOUSE_OFFSET, handlerRect.rightBottom().y()) + MOUSE_OFFSET
                )
        );
        // 10. 登录处理（监听登录 Ajax 结果）
        rpa().newHar();
        rpa().click(By.cssSelector("button.el-button.loginCls"), WAIT_TIME);
        var response = rpa().jsonListen("auth/user/single/userNamePswLogin", SysApiResponse.class);
        if (!response.success()) {
            throw new EtaxException(response.msg());
        }
    }
}
